package com.jinlei.crm.settings.controller;

import com.jinlei.crm.commons.utils.DateUtil;
import com.jinlei.crm.commons.utils.MD5Util;
import com.jinlei.crm.commons.utils.Result;
import com.jinlei.crm.settings.entity.User;
import com.jinlei.crm.settings.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(String loginAct, String loginPwd, HttpSession session) {
        // 根据用户提交的账号  查询用户是否存在  hah
        User loginUser = userService.findByLoginAct(loginAct);

        if (loginUser == null) {
            return Result.error(-2, "用户不存在");
        }
        if (!loginUser.getLoginPwd().equals(MD5Util.getMD5(loginPwd))) {
            return Result.error(-3, "登录账户或密码有误");
        }
        if ("0".equals(loginUser.getLockState())) {
            return Result.error(-4, "该账户已锁定");
        }
        // 失效时间
        if(StringUtils.hasLength(loginUser.getExpireTime()) && new Date().compareTo(DateUtil.formatString(loginUser.getExpireTime())) > 0){
            return Result.error(-5, "该账户已失效");
        }
        // 通过判断就代表登录成功
        session.setAttribute("loginUser",loginUser);
        // ip 判断
        return Result.success(loginUser);
    }

    @GetMapping("/logout")
    public Result logout(HttpSession session){
        session.removeAttribute("loginUser");
        session.invalidate();
        return Result.success();
    }
}
